<template>
  <div class="project-management">
    <header class="header">
      <h1>太原赵北峰城中村改造地块-(二期)工程项目</h1>
      <div class="user-info">
        <span class="user-name">{{ currentUser.name }}</span>
        <span class="user-role">工种：{{ currentUser.role }}</span>
        <span class="completion-rate">新合格率：{{ currentUser.completionRate }}</span>
      </div>
    </header>

    <div class="main-content">
      <!-- 人员统计部分 -->
      <div class="statistics-panel">
        <div class="total-stats">
          <div class="stat-item">
            <h3>项目工人总数</h3>
            <div class="number">{{ statistics.totalWorkers }}</div>
          </div>
          <div class="current-stats">
            <div class="stat-row">
              <span>当前现场总人数</span>
              <span class="highlight">{{ statistics.currentTotal }}</span>
            </div>
            <div class="stat-row">
              <span>当前现场工人数</span>
              <span class="highlight">{{ statistics.currentWorkers }}</span>
            </div>
            <div class="stat-row">
              <span>现场管理人员</span>
              <span class="highlight">{{ statistics.managers }}</span>
            </div>
          </div>
        </div>

        <!-- 工种分布统计表格 -->
        <WorkTypeStats
          :data="workTypeStats"
          :loading="loading"
          @showDetail="showWorkTypeDetail"
        />

        <!-- 班组分布统计表格 -->
        <TeamStats
          :data="teamStats"
          :loading="loading"
          @showDetail="showTeamDetail"
          @showMembers="showTeamMembers"
        />
      </div>

      <!-- 3D建筑模型部分 -->
      <div class="building-model">
        <div class="model-container">
          <!-- 这里将放置3D模型，暂时用图片替代 -->
          <img :src="buildingModelSrc" alt="建筑模型" />
        </div>
        <FloorPersonnelList
          :data="floors"
          @showDetail="showFloorDetail"
        />
      </div>

      <!-- 右侧统计信息 -->
      <div class="right-panel">
        <PersonnelTrack
          :data="statusList"
          :loading="loading"
          @showDetail="showStatusDetail"
        />
        
        <div class="charts">
          <WorkDistribution
            :data="workTypeStats"
          />
          <PersonnelStats
            :data="personnelData"
          />
        </div>
      </div>
    </div>

    <!-- 详情模态框 -->
    <a-modal
      v-model:visible="detailModalVisible"
      :title="detailModalTitle"
      @ok="handleDetailModalOk"
      @cancel="handleDetailModalCancel"
    >
      <div v-if="currentDetailData">
        <a-descriptions bordered>
          <a-descriptions-item v-for="(value, key) in currentDetailData" :key="key" :label="key">
            {{ value }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import WorkTypeStats from '@/components/WorkTypeStats.vue'
import TeamStats from '@/components/TeamStats.vue'
import PersonnelStats from '@/components/PersonnelStats.vue'
import WorkDistribution from '@/components/WorkDistribution.vue'
import PersonnelTrack from '@/components/PersonnelTrack.vue'
import FloorPersonnelList from '@/components/FloorPersonnelList.vue'

const currentUser = ref({
  name: 'xxxx巧务队',
  role: '木工',
  completionRate: '82%'
})

const statistics = ref({
  totalWorkers: 4256,
  currentTotal: 16,
  currentWorkers: 14,
  managers: 2
})

// 搜索和筛选状态
const workTypeSearchText = ref('')
const teamSearchText = ref('')
const loading = ref(false)

// 图表类型选择
const pieChartType = ref('count')
const barChartType = ref('daily')

// 模态框状态
const detailModalVisible = ref(false)
const detailModalTitle = ref('')
const currentDetailData = ref(null)

// 表格列定义更新
const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    width: 80,
    sorter: (a, b) => a.id.localeCompare(b.id),
  },
  {
    title: '工种类型',
    dataIndex: 'type',
    sorter: (a, b) => a.type.localeCompare(b.type),
  },
  {
    title: '在场人数',
    dataIndex: 'count',
    width: 100,
    align: 'right',
    sorter: (a, b) => a.count - b.count,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 80,
    fixed: 'right',
  }
]

// 工种数据
const workTypeStats = ref([
  { key: '1', id: '01', type: '钢筋工', count: 121 },
  { key: '2', id: '02', type: '木工', count: 98 },
  { key: '3', id: '03', type: '泥工', count: 85 },
  { key: '4', id: '04', type: '电工', count: 76 },
  { key: '5', id: '05', type: '焊工', count: 62 }
])

const floors = ref([
  { level: 1, currentCount: 16, totalBeds: 20 },
  { level: 2, currentCount: 16, totalBeds: 20 },
  { level: 3, currentCount: 16, totalBeds: 20 },
  { level: 4, currentCount: 14, totalBeds: 20 },
  { level: 5, currentCount: 12, totalBeds: 20 }
])

const statusList = ref([
  {
    name: '施工中',
    state: '正常',
    area: '2F/10#楼施工区域',
    qualificationRate: '82%'
  },
  {
    name: '施工中',
    state: '正常',
    area: '3F/10#楼施工区域',
    qualificationRate: '85%'
  }
])

// ECharts 实例引用
const pieChartRef = ref(null)
const barChartRef = ref(null)
let pieChart = null
let barChart = null

// 饼图配置
const pieChartOption = {
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    textStyle: {
      color: '#fff'
    }
  },
  series: [
    {
      name: '工种分布',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '20',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 121, name: '钢筋工' },
        { value: 98, name: '木工' },
        { value: 85, name: '泥工' },
        { value: 76, name: '电工' },
        { value: 62, name: '焊工' }
      ]
    }
  ]
}

// 柱状图配置
const barChartOption = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    axisLine: {
      lineStyle: {
        color: '#fff'
      }
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '#fff'
      }
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.1)'
      }
    }
  },
  series: [
    {
      name: '在场人数',
      type: 'bar',
      barWidth: '60%',
      data: [152, 165, 148, 178, 160, 145, 138],
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
}

// 班组表格列定义更新
const teamColumns = [
  {
    title: '班组名称',
    dataIndex: 'name',
    width: 120,
    sorter: (a, b) => a.name.localeCompare(b.name),
  },
  {
    title: '人数',
    dataIndex: 'memberCount',
    width: 80,
    align: 'right',
    sorter: (a, b) => a.memberCount - b.memberCount,
  },
  {
    title: '完成率',
    dataIndex: 'completion',
    width: 180,
    sorter: (a, b) => Number(a.completion.replace('%', '')) - Number(b.completion.replace('%', '')),
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 120,
    fixed: 'right',
  }
]

// 班组数据
const teamStats = ref([
  // 钢筋班组
  { key: 's1', type: 'steel', name: '钢筋一班', memberCount: 45, completion: '85%' },
  { key: 's2', type: 'steel', name: '钢筋二班', memberCount: 38, completion: '92%' },
  { key: 's3', type: 'steel', name: '钢筋三班', memberCount: 38, completion: '78%' },
  // 木工班组
  { key: 'w1', type: 'wood', name: '木工一班', memberCount: 32, completion: '88%' },
  { key: 'w2', type: 'wood', name: '木工二班', memberCount: 35, completion: '76%' },
  { key: 'w3', type: 'wood', name: '木工三班', memberCount: 31, completion: '82%' },
  // 泥工班组
  { key: 'm1', type: 'mason', name: '泥工一班', memberCount: 28, completion: '90%' },
  { key: 'm2', type: 'mason', name: '泥工二班', memberCount: 30, completion: '85%' },
  { key: 'm3', type: 'mason', name: '泥工三班', memberCount: 27, completion: '79%' },
])

// 选中的班组类型
const selectedTeamType = ref('all')

// 工种数据过滤
const filteredWorkTypeStats = computed(() => {
  if (!workTypeSearchText.value) return workTypeStats.value
  const searchText = workTypeSearchText.value.toLowerCase()
  return workTypeStats.value.filter(item => 
    item.type.toLowerCase().includes(searchText) ||
    item.id.includes(searchText)
  )
})

// 班组数据过滤
const filteredTeamStats = computed(() => {
  let result = teamStats.value
  
  // 按类型筛选
  if (selectedTeamType.value !== 'all') {
    result = result.filter(team => team.type === selectedTeamType.value)
  }
  
  // 按搜索文本筛选
  if (teamSearchText.value) {
    const searchText = teamSearchText.value.toLowerCase()
    result = result.filter(team => 
      team.name.toLowerCase().includes(searchText)
    )
  }
  
  return result
})

// 处理搜索
const handleWorkTypeSearch = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 300)
}

const handleTeamSearch = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 300)
}

// 获取完成状态描述
const getCompletionStatus = (completion) => {
  const value = Number(completion.replace('%', ''))
  if (value >= 90) return '优秀'
  if (value >= 80) return '良好'
  if (value >= 70) return '一般'
  return '需改进'
}

// 显示详情模态框
const showWorkTypeDetail = (record) => {
  currentDetailData.value = {
    '工种类型': record.type,
    '在场人数': record.count,
    '工种编号': record.id,
    '工作区域': '2F-10F',
    '负责人': '张三',
    '联系方式': '13800138000'
  }
  detailModalTitle.value = '工种详情'
  detailModalVisible.value = true
}

const showTeamDetail = (record) => {
  currentDetailData.value = {
    '班组名称': record.name,
    '人数': record.memberCount,
    '完成率': record.completion,
    '班组长': '李四',
    '联系方式': '13900139000',
    '工作区域': '3F-8F',
    '当前任务': '钢筋绑扎'
  }
  detailModalTitle.value = '班组详情'
  detailModalVisible.value = true
}

const showTeamMembers = (record) => {
  // 这里可以显示班组成员列表
  detailModalTitle.value = '班组成员'
  currentDetailData.value = {
    '班组长': '李四',
    '副班长': '王五',
    '成员1': '张三',
    '成员2': '李四',
    '成员3': '王五'
  }
  detailModalVisible.value = true
}

const showStatusDetail = (status) => {
  currentDetailData.value = {
    '状态': status.name,
    '区域': status.area,
    '新合格率': status.qualificationRate,
    '开始时间': '2024-03-20',
    '预计完成': '2024-04-20',
    '负责人': '张三',
    '联系方式': '13800138000'
  }
  detailModalTitle.value = '状态详情'
  detailModalVisible.value = true
}

// 模态框操作
const handleDetailModalOk = () => {
  detailModalVisible.value = false
}

const handleDetailModalCancel = () => {
  detailModalVisible.value = false
}

// 更新图表显示
const updatePieChart = () => {
  if (!pieChart) return
  
  const option = {
    ...pieChartOption,
    series: [{
      ...pieChartOption.series[0],
      data: pieChartType.value === 'count' 
        ? workTypeStats.value.map(item => ({ value: item.count, name: item.type }))
        : teamStats.value.map(item => ({ 
            value: Number(item.completion.replace('%', '')), 
            name: item.name 
          }))
    }]
  }
  pieChart.setOption(option)
}

const updateBarChart = () => {
  if (!barChart) return
  
  const getBarData = () => {
    switch (barChartType.value) {
      case 'daily':
        return {
          xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          data: [152, 165, 148, 178, 160, 145, 138]
        }
      case 'weekly':
        return {
          xAxis: ['第一周', '第二周', '第三周', '第四周'],
          data: [755, 820, 890, 780]
        }
      case 'monthly':
        return {
          xAxis: ['1月', '2月', '3月', '4月'],
          data: [3200, 3500, 3800, 3600]
        }
    }
  }

  const { xAxis: xAxisData, data } = getBarData()
  const option = {
    ...barChartOption,
    xAxis: {
      ...barChartOption.xAxis,
      data: xAxisData
    },
    series: [{
      ...barChartOption.series[0],
      data: data
    }]
  }
  barChart.setOption(option)
}

// 初始化图表
onMounted(() => {
  loading.value = true
  
  // 初始化饼图
  pieChart = echarts.init(pieChartRef.value)
  pieChart.setOption(pieChartOption)

  // 初始化柱状图
  barChart = echarts.init(barChartRef.value)
  barChart.setOption(barChartOption)

  // 添加图表点击事件
  pieChart.on('click', (params) => {
    const workType = workTypeStats.value.find(item => item.type === params.name)
    if (workType) {
      showWorkTypeDetail(workType)
    }
  })

  // 添加窗口大小变化的监听
  window.addEventListener('resize', handleResize)
  
  setTimeout(() => {
    loading.value = false
  }, 500)
})

// 处理窗口大小变化
const handleResize = () => {
  pieChart?.resize()
  barChart?.resize()
}

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  pieChart?.dispose()
  barChart?.dispose()
})

// 处理班组类型切换
const handleTeamTypeChange = (value) => {
  selectedTeamType.value = value
}

// 获取进度条颜色
const getProgressColor = (completion) => {
  const value = Number(completion.replace('%', ''))
  if (value >= 90) return '#67C23A'
  if (value >= 80) return '#409EFF'
  if (value >= 70) return '#E6A23C'
  return '#F56C6C'
}
</script>

<style scoped>
.project-management {
  background-color: #1a1f2c;
  color: #fff;
  min-height: 100vh;
  padding: 2vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5vh 2vw;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  margin-bottom: 2vh;
  height: 8vh;
}

.header h1 {
  font-size: 2.4vh;
  margin: 0;
}

.user-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.user-info span {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 6px 12px;
  border-radius: 4px;
}

.main-content {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr;
  gap: 2vh;
  height: 86vh; /* 考虑到头部8vh和padding 2vh */
  overflow: hidden;
}

.statistics-panel {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 2vh;
  display: flex;
  flex-direction: column;
  gap: 2vh;
  height: 100%;
  overflow-y: auto;
}

.total-stats {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  padding: 1.5vh;
  min-height: 15vh;
}

.stat-item {
  margin-bottom: 20px;
}

.stat-item h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #409EFF;
}

.number {
  font-size: 3.2vh;
  font-weight: bold;
  color: #fff;
}

.current-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.work-type-stats {
  background-color: rgb(0 20 53 / 79%);
  border-radius: 8px;
  padding: 1.5vh;
  height: calc(35vh - 2vh);
  display: flex;
  flex-direction: column;
}

.work-type-stats h3 {
  margin: 0 0 15px 0;
  color: #409EFF;
  font-size: 16px;
}

.building-model {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 2vh;
  display: flex;
  gap: 2vh;
  height: 86vh;
}

.model-container {
  flex: 2;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.model-container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.floor-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1vh;
  padding: 1vh;
  height: 100%;
  overflow-y: auto;
}

.floor-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
}

.floor-level {
  font-weight: bold;
  color: #409EFF;
}

.floor-stats {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 14px;
}

.right-panel {
  background-color: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  padding: 2vh;
  display: flex;
  flex-direction: column;
  gap: 2vh;
  height: 86vh;
}

.status-cards {
  display: flex;
  flex-direction: column;
  gap: 1vh;
  height: 30vh;
  overflow-y: auto;
}

.status-card {
  cursor: pointer;
  transition: all 0.3s;
}

.status-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.status-indicator {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-indicator.正常 {
  background-color: #67C23A;
}

.status-indicator.异常 {
  background-color: #F56C6C;
}

.charts {
  flex: 1;
  display: grid;
  grid-template-rows: 1fr 1fr;
  gap: 2vh;
  height: calc(56vh - 2vh);
}

.chart-container {
  background-color: rgba(255, 255, 255, 0.05);
  background-color: rgb(0 20 53 / 79%);
  border-radius: 6px;
  padding: 1.5vh;
  height: 100%;
}

.chart-container h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #409EFF;
}

.chart {
  height: calc(100% - 5vh);
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
    height: auto;
    overflow: visible;
  }
  
  .building-model {
    flex-direction: column;
    height: auto;
  }
  
  .model-container {
    height: 50vh;
  }
  
  .floor-info {
    height: 30vh;
  }
  
  .right-panel {
    height: auto;
  }
  
  .charts {
    height: auto;
  }
  
  .chart {
    height: 40vh;
  }
  
  .work-type-stats, .team-stats {
    height: auto;
  }
}

/* 自定义 Ant Design Vue Table 样式 */
:deep(.ant-table) {
  background-color: transparent;
  color: #fff;
}

:deep(.ant-table-thead > tr > th) {
  background-color: rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.ant-table-tbody > tr > td) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background-color: transparent !important;
  color: #fff;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

:deep(.ant-table-tbody > tr.ant-table-row:hover > td) {
  background-color: rgba(255, 255, 255, 0.05) !important;
}

/* 移除表格的边框 */
:deep(.ant-table-container) {
  border: none !important;
}

:deep(.ant-table-thead > tr > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

/* 滚动条样式 */
:deep(.ant-table-body::-webkit-scrollbar) {
  width: 6px;
  background-color: transparent;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background-color: transparent;
}

.team-stats {
  background-color: rgba(255, 255, 255, 0.05);
  background-color: rgb(0 20 53 / 79%);
  border-radius: 8px;
  padding: 1.5vh;
  margin-top: 2vh;
}

.team-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.team-header h3 {
  margin: 0;
  color: #409EFF;
  font-size: 16px;
}

.team-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.completion-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-icon {
  color: #409EFF;
  cursor: pointer;
}

/* Select 组件样式 */
:deep(.ant-select) {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

:deep(.ant-select-selector) {
  background-color: transparent !important;
  border: none !important;
  color: #fff !important;
}

:deep(.ant-select-arrow) {
  color: #fff;
}

:deep(.ant-select-dropdown) {
  background-color: #1a1f2c;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.ant-select-item) {
  color: #fff !important;
}

:deep(.ant-select-item-option-active:not(.ant-select-item-option-disabled)) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.ant-select-item-option-selected:not(.ant-select-item-option-disabled)) {
  background-color: rgba(64, 158, 255, 0.2) !important;
}

/* Progress 组件样式 */
:deep(.ant-progress-text) {
  color: #fff !important;
}

:deep(.ant-progress-inner) {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.table-header, .team-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

/* Ant Design Vue 组件样式覆盖 */
:deep(.ant-input-search-button) {
  background-color: #409EFF !important;
  border-color: #409EFF !important;
}

:deep(.ant-radio-button-wrapper) {
  background: transparent !important;
  border-color: rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
}

:deep(.ant-radio-button-wrapper-checked) {
  background: #409EFF !important;
  border-color: #409EFF !important;
}

:deep(.ant-modal-content),
:deep(.ant-modal-header) {
  background-color: #1a1f2c !important;
  color: #fff !important;
}

:deep(.ant-modal-title) {
  color: #fff !important;
}

:deep(.ant-modal-close-icon) {
  color: #fff !important;
}

:deep(.ant-descriptions) {
  color: #fff !important;
}

:deep(.ant-descriptions-item-label),
:deep(.ant-descriptions-item-content) {
  background-color: rgba(255, 255, 255, 0.05) !important;
  border-color: rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
}
</style> 